package com.turing.data.scripts.xgpsgg.filter

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.turing.common.util.FileUtils
import com.turing.common.util.Log
import com.turing.common.util.StringUtils
import com.turing.data.vo.out.review.DependParamsVO
import com.turing.data.vo.out.review.TaskElementVO

import java.util.regex.Matcher
import java.util.regex.Pattern

class WinningPrice_12356_r15_filter {

    public static void main(String[] args) {
        DependParamsVO param = new DependParamsVO()
        param.setJSONPathMap(new LinkedHashMap<String, String>())
//        param.getJSONPathMap().put("abc", "http://media.tlrobot.com/group1/M00/0C/29/rBIHD2CjdRiAPV_eAACdNH_q44831.json")
//        param.getJSONPathMap().put("abc", "/Users/luoshiwei/Desktop/tmp/ex/extractor/e675314b-1c3b-4bb7-9a9f-ef5c268b7b6d/688316_20210305_1/json/688316_20210305_1_converted.json")
        param.getJSONPathMap().put("abc", "C:\\Users\\14771\\Desktop\\楚天龙：首次公开发行股票网下发行初步配售结果公告_converted.json")
        List<TaskElementVO.DrawResultVO> s = doConvert(param)
        for (int z = 0; z < s.size(); z++) {
            def get = s.get(z)
            println(get.text)
        }
    }

    static List<TaskElementVO.DrawResultVO> doConvert(DependParamsVO dependParams ) {
        def keyWord = /(?<![(（])元\/(股|张)(?![)）])/
        def keyWord2 = /(本次)?发行的?价格/
        def REGEX = /(?<=(本次)?发行的?价格为?(人民币)?\s{0,2})\d{1,10}(\.\d{0,2})?(?=\s{0,2}元\/(股|张))/

        Pattern keyWordPattern = Pattern.compile(keyWord);
        Pattern keyWordPattern2 = Pattern.compile(keyWord2);
        Pattern fullPattern = Pattern.compile(REGEX);

        Date begin = new Date()
        Date end = new Date()

        List<String> titleList = new LinkedList<>()
        Map<String, String> oldAndNewTitleMap = new HashMap<>()
        Map<String, String> titleAndValueMap = new HashMap<>()

        List<String> keys = dependParams.getJSONPathMap().keySet() as List<String>
        List<TaskElementVO.DrawResultVO> finalResults = new ArrayList<>()

        for (int z = 0; z < keys.size(); z++) {

            String path = dependParams.getJSONPathMap().get(keys.get(z))
            String format_json_path = "/Users/luoshiwei/Desktop/response.json"

            if (!StringUtils.isEmpty(path)) {
                format_json_path = path
            }

            begin = new Date()
            String jsonString = FileUtils.loadJson(format_json_path)
            end = new Date()
            println "load json: " + (end.getTime() - begin.getTime()) / 1000 / 1000

            begin = new Date()
            JSONArray formatArr = JSONArray.parse(jsonString)
            end = new Date()
            println "parse json array: " + (end.getTime() - begin.getTime()) / 1000 / 1000
            begin = new Date()
            println begin

            for (int pageNo = 0; pageNo < formatArr.size(); pageNo++) {
                JSONObject pageObj = formatArr.getJSONObject(pageNo)
                JSONArray paraArr = pageObj.getJSONArray("paragraphs")
                for (int paragraphsNo = 0; paragraphsNo < paraArr.size(); paragraphsNo++) {

                    JSONObject paraObj = paraArr.getJSONObject(paragraphsNo)
                    JSONArray lineArr = paraObj.getJSONArray("lines")
                    //每一行
                    for (int line = 0; line < lineArr.size(); line++) {
                        titleAndValueMap = new HashMap<>()
                        JSONObject lineObj = lineArr.getJSONObject(line)
                        String lineId = lineObj.getString("lineId")
                        String objType = lineObj.getString("objType")
                        if (JSON.isValidArray(lineObj.getString("objContent")) || objType == "table") {
                            continue
                        }
                        String objContentString = lineObj.getString("objContent")
                        if (!StringUtils.isEmpty(objContentString)) {
                            Matcher matcher = fullPattern.matcher(objContentString)
                            Matcher keyWordmatcher = keyWordPattern.matcher(objContentString);
                            Matcher keyWordmatcher2 = keyWordPattern2.matcher(objContentString);
                            if (matcher.find()) {
                                def str = matcher.group()
                                //println(str)
                                def cWordCount = str.length()

                                def startPoint = objContentString.indexOf(str)
                                def endPoint = startPoint + cWordCount

                                TaskElementVO.DrawResultVO drawResultVO = new TaskElementVO.DrawResultVO()
                                drawResultVO.setBusinessValue(str)
                                drawResultVO.setText(str)
                                drawResultVO.setPara_info([lineId])
                                drawResultVO.setPos_info([startPoint, endPoint])
                                drawResultVO.setPage(lineId.split("_")[1] as Integer)
                                drawResultVO.setChildTaskSn(keys.get(z))
                                drawResultVO.setType(1)
                                finalResults.add(drawResultVO)
                                return finalResults
                            } else if (keyWordmatcher.find()) {
                                JSONObject lastLineObj = lineArr.getJSONObject(line - 1)
                                String lastLineId = lastLineObj.getString("lineId")
                                String lastObjContentString = lastLineObj.getString("objContent")
                                def thisLineContent = objContentString
                                objContentString = lastObjContentString + objContentString
                                matcher = fullPattern.matcher(objContentString)
                                if (matcher.find()) {
                                    def str = matcher.group()
                                    //println(str)
                                    def cWordCount = str.length()


                                    def startPoint = 0
                                    def endPoint = cWordCount
                                    if (lastObjContentString.contains(str)) {
                                        startPoint = lastObjContentString.indexOf(str)
                                    } else {
                                        startPoint = thisLineContent.indexOf(str)
                                    }
                                    endPoint = startPoint + cWordCount

                                    def valueLineId = lastLineId
                                    if (thisLineContent.contains(str)) {
                                        valueLineId = lineId
                                    }

                                    TaskElementVO.DrawResultVO drawResultVO = new TaskElementVO.DrawResultVO()
                                    drawResultVO.setBusinessValue(str)
                                    drawResultVO.setText(str)
                                    drawResultVO.setPara_info([valueLineId])
                                    drawResultVO.setPos_info([startPoint, endPoint])
                                    drawResultVO.setPage(lastLineId.split("_")[1] as Integer)
                                    drawResultVO.setChildTaskSn(keys.get(z))
                                    drawResultVO.setType(1)
                                    finalResults.add(drawResultVO)
                                    return finalResults
                                }
                            } else if (keyWordmatcher2.find()) {
                                JSONObject lastLineObj = lineArr.getJSONObject(line + 1)
                                String lastLineId = lastLineObj.getString("lineId")
                                String lastObjContentString = lastLineObj.getString("objContent")
                                def thisLineContent = objContentString
                                objContentString = objContentString + lastObjContentString
                                matcher = fullPattern.matcher(objContentString)
                                if (matcher.find()) {
                                    def str = matcher.group()
                                    //println(str)
                                    def cWordCount = str.length()


                                    def startPoint = 0
                                    def endPoint = cWordCount
                                    if (lastObjContentString.contains(str)) {
                                        startPoint = lastObjContentString.indexOf(str)
                                    } else {
                                        startPoint = thisLineContent.indexOf(str)
                                    }
                                    endPoint = startPoint + cWordCount

                                    def valueLineId = lastLineId
                                    if (thisLineContent.contains(str)) {
                                        valueLineId = lineId
                                    }

                                    TaskElementVO.DrawResultVO drawResultVO = new TaskElementVO.DrawResultVO()
                                    drawResultVO.setBusinessValue(str)
                                    drawResultVO.setText(str)
                                    drawResultVO.setPara_info([valueLineId])
                                    drawResultVO.setPos_info([startPoint, endPoint])
                                    drawResultVO.setPage(lastLineId.split("_")[1] as Integer)
                                    drawResultVO.setChildTaskSn(keys.get(z))
                                    drawResultVO.setType(1)
                                    finalResults.add(drawResultVO)
                                    return finalResults
                                }
                            }
                        }
                    }
                }
            }

            end = new Date()
            println end
            println "ex elements: " + (end.getTime() - begin.getTime()) / 1000 / 1000
        }


        if(finalResults.size()==0){
            TaskElementVO.DrawResultVO defaultDrawResultVO = new TaskElementVO.DrawResultVO()
            defaultDrawResultVO.text = ""
            finalResults.add(defaultDrawResultVO)
        }
        Log.info(">>>>>>>>>>>>>>>>>中签价格的结果对象有"+finalResults.size()+"个")
        return finalResults
    }

    static boolean arrContains(String[] Search_Titles, String objContentString) {
        if (Search_Titles.contains(objContentString)) {
            return true
        }
        for (i in 0..<Search_Titles.length) {
            String title = Search_Titles[i]
            title = title.replaceAll(" ", "")
                    .replaceAll("（", "(")
                    .replaceAll("）", ")")
                    .replaceAll("万", "")
            String anoContentString = objContentString.replaceAll(" ", "")
                    .replaceAll("（", "(")
                    .replaceAll("）", ")")
                    .replaceAll("万", "")
            if (title == anoContentString) {
                return true
            }

        }

        return false
    }
}
